from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime
import os


def init_photo_upload_routes(app):
    # 确保上传目录存在
    UPLOAD_FOLDER = 'uploads'
    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER)

    def save_file(file):
        filename = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{file.filename}"
        file_path = os.path.join(UPLOAD_FOLDER, filename)
        file.save(file_path)
        return file_path

    @app.route('/api/upload', methods=['POST'])
    @jwt_required()
    def upload_image():
        try:
            current_user = get_jwt_identity()
            file = request.files.get('image')

            if not file:
                return jsonify({'success': False, 'message': '没有收到文件'}), 400

            # 检查文件类型
            if not file.filename.lower().endswith(('.png', '.jpg', '.jpeg')):
                return jsonify({'success': False, 'message': '只支持PNG/JPG格式'}), 400

            # 保存文件并更新数据库
            file_path = save_file(file)

            # 更新用户历史记录
            cursor = mysql.connection.cursor()
            cursor.execute("""
                INSERT INTO user_history (username, upload_img, upload_time)
                VALUES (%s, %s, %s)
            """, (current_user, file_path, datetime.now()))
            mysql.connection.commit()
            cursor.close()

            return jsonify({
                'success': True,
                'message': '上传成功',
                'file_path': file_path
            })

        except Exception as e:
            return jsonify({
                'success': False,
                'message': str(e)
            }), 500

    return app